package com.demo1224.servlet;

import com.demo1224.entity.User;
import com.demo1224.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/demo1224/login.do")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User login = userService.login(username, password);
        PrintWriter writer = resp.getWriter();
        if (login == null) {
            writer.write("<h1>用户名或密码错误！</h1>");
            resp.sendRedirect("./login.jsp");
        } else {
            req.getSession().setAttribute("user", login);
            req.getRequestDispatcher("/demo1224/user/index.jsp").forward(req, resp);
        }
    }
}
